<?

include_once 'lib/facebook.php';
include_once 'includes/config.php';
include_once 'includes/dbconnect.php';


$question_id = $_POST['question_id'];
$answer = $_POST['answer'];
$fb_id = $_SESSION['fb_id'];
$is_first_time = 0;

$chk_first_time = mysql_query("select count(*) as result from tbl_answer where fb_id='$fb_id'");
if (mysql_result($chk_first_time, 0, "result") == 0) {
    $is_first_time = 1;
}

$chk = mysql_query("select * from tbl_answer where question_id='$question_id' and fb_id='$fb_id'");

if (mysql_num_rows($chk) > 0) {
    $id = mysql_result($chk, 0, "id");
    mysql_query("update tbl_answer set answer='$answer' where id='$id'");
} else {

    mysql_query("insert into tbl_answer(question_id,fb_id,answer,created_datetime)values('$question_id','$fb_id','$answer',now())") or die(mysql_error());
}


$get_question = mysql_query("select * from tbl_question where id='$question_id'");
$q = mysql_fetch_assoc($get_question);


//$is_first_time=1;
if ($is_first_time == 1) {

    $get_yes = mysql_query("select count(*) as result from tbl_answer where answer='Y' and question_id='$question_id'");
    $get_no = mysql_query("select count(*) as result from tbl_answer where answer='N' and question_id='$question_id'");

    $total_yes = mysql_result($get_yes, 0, "result");
    $total_no = mysql_result($get_no, 0, "result");
    $yes_percent = $no_percent = 0;

    if ($total_yes > 0) {
        $yes_percent = number_format(($total_yes / ($total_yes + $total_no)) * 100, 0);
    }

    //$share_copy = str_replace("[percent]", "$yes_percent", $q['share_copy']);
    
    $share_copy = "Digital banking matters to me. What's your take? Give your opinions here! ";

    $api_call = array(
        'method' => 'users.hasAppPermission',
        'uid' => $fb_id,
        'ext_perm' => 'publish_stream'
    );

    $can_post = $facebook->api($api_call);
    
    
    if ($can_post) {
        # post it! 
        $facebook->api('/' . $fb_id . '/feed', 'post', array(
            'message' => '',
            'name' => FACEBOOK_APP_NAME,
            'description' => $share_copy,
            'picture' => "http://www.dciapp.com/maybank/whats-your-take/fb-app/images/logo.gif",
            'link' => FACEBOOK_PAGE_TAB_URL
                )
        );
    }
}
?>
